import {
  updateUserInfo
} from '@/api/api';
import { Validator } from '@/utils/validator';
import Toast from '@vant/weapp/toast/toast';
import { globalRouteGuard } from "@/utils/auth";

Page({
  data: {
    oldUserInfo: {
      username: '',
      avatar: '',
      wechatId: '',
      qqId: ''
    },
    userInfo: {
      username: '',
      avatar: '',
      wechatId: '',
      qqId: ''
    },
    isLoading: false,
    errorMessages: {
      username: '',
      wechatId: '',
      qqId: ''
    },
    uploading: false,
    progress: 0
  },
  onLoad() {
    // 使用全局路由守卫检查登录状态
    if (!globalRouteGuard('/pages/editUserInfo/editUserInfo')) {
      return;
    }
    const userInfo = getApp().userInfo;
    this.setData({
      userInfo: { ...userInfo },
      oldUserInfo: { ...userInfo }
    });
  },

  // 选择头像
  chooseAvatar() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        // 调用上传方法
        this.uploadAvatar(tempFilePath);
      },
      fail: (err) => {
        console.error('选择图片失败:', err);
      }
    });
  },

  // 上传头像
  uploadAvatar(filePath) {
    this.setData({
      uploading: true,
      progress: 0
    });

    // 直接使用wx.uploadFile上传文件
    const uploadTask = wx.uploadFile({
      url: 'http://127.0.0.1:8080/other/fileUpload', // 服务器地址
      filePath: filePath,
      name: 'file', // 后端接收文件的字段名
      header: {
        'Authorization': getApp().Authorization || '', // 添加认证信息
      },
      success: (res) => {
        this.setData({
          progress: 100
        });

        // 解析返回的数据
        let result;
        try {
          result = JSON.parse(res.data);
        } catch (e) {
          console.error('解析返回数据失败', e);
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
          this.setData({
            uploading: false
          });
          return;
        }

        // 检查上传是否成功
        if (res.statusCode === 200 && result.code === 200) {
          // 获取上传后的图片URL
          const imageUrl = result.fileUrl || result.url || result.data;
          this.setData({
            'userInfo.avatar': imageUrl,
            uploading: false
          });
          wx.showToast({
            title: '头像上传成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
          this.setData({
            uploading: false
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        });
        console.error('上传失败', err);
        this.setData({
          uploading: false
        });
      }
    });

    // 监听上传进度
    uploadTask.onProgressUpdate((res) => {
      this.setData({
        progress: res.progress
      });
    });
  },

  // 用户名输入
  onUsernameInput(e) {
    const value = e.detail;
    this.setData({
      'userInfo.username': value
    });
    // 输入时实时校验
    const result = Validator.validateUsername(value);
    this.setData({
      'errorMessages.username': result.message
    });
  },

  // 微信 ID 输入
  onWechatIdInput(e) {
    const value = e.detail;
    this.setData({
      'userInfo.wechatId': value
    });
    // 输入时实时校验
    const result = Validator.validateWechatId(value);
    this.setData({
      'errorMessages.wechatId': result.message
    });
  },

  // QQ ID 输入
  onQqIdInput(e) {
    const value = e.detail;
    this.setData({
      'userInfo.qqId': value
    });
    // 输入时实时校验
    const result = Validator.validateQqId(value);
    this.setData({
      'errorMessages.qqId': result.message
    });
  },

  // 表单校验
  validateForm() {
    const { userInfo } = this.data;
    const usernameResult = Validator.validateUsername(userInfo.username);
    const wechatIdResult = Validator.validateWechatId(userInfo.wechatId);
    const qqIdResult = Validator.validateQqId(userInfo.qqId);

    const errorMessages = {
      username: usernameResult.message,
      wechatId: wechatIdResult.message,
      qqId: qqIdResult.message
    };

    this.setData({ errorMessages });

    return [usernameResult, wechatIdResult, qqIdResult].every(result => result.isValid);
  },

  // 保存用户信息
  async saveUserInfo() {
    if (this.data.isLoading) return;

    const isValid = this.validateForm();
    if (!isValid) {
      return Toast.fail('请填写正确的信息');
    }
    this.setData({ isLoading: true });

    try {
      const res = await updateUserInfo(this.data.userInfo);
      if (res.code === 200) {
        // 刷新全局用户信息
        getApp().userInfo = this.data.userInfo;
        this.setData({ oldUserInfo: this.data.userInfo });
        setTimeout(() => {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          });
        }, 600)
        wx.navigateBack();
      } else {
        throw new Error('保存失败');
      }
    } catch (error) {
      console.error('保存用户信息失败:', error);
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      });
    } finally {
      this.setData({ isLoading: false });
    }
  },

  onClickLeft() {
    wx.navigateBack();
    this.setData({
      userInfo: { ...this.data.oldUserInfo }
    })
  }
});